<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>班级管理</span>
        <div class="header-actions">
          <el-button type="primary" @click="handleAdd">新增班级</el-button>
          <el-button @click="handleRefresh">刷新</el-button>
        </div>
      </div>
    </template>

    <!-- 搜索条件 -->
    <el-form :model="searchForm" label-width="80px" class="search-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="班级名称">
            <el-input v-model="searchForm.name" placeholder="请输入班级名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="active" />
              <el-option label="归档" value="archived" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="毕业状态">
            <el-select v-model="searchForm.graduationStatus" placeholder="请选择毕业状态" clearable>
              <el-option label="在读" value="studying" />
              <el-option label="已毕业" value="graduated" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 班级列表 -->
    <el-table :data="classList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="班级名称" width="150" />
      <el-table-column prop="collegeName" label="所属学院" width="120" />
      <el-table-column prop="majorName" label="所属专业" width="120" />
      <el-table-column prop="grade" label="年级" width="100" />
      <el-table-column prop="semester" label="学期" width="120" />
      <el-table-column prop="studentCount" label="学生人数" width="100" />
      <el-table-column prop="headTeacherName" label="班主任" width="120" />
      <el-table-column prop="graduationStatus" label="毕业状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.graduationStatus === 'studying' ? 'primary' : 'success'">
            {{ scope.row.graduationStatus === 'studying' ? '在读' : '已毕业' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
            {{ scope.row.status === 'active' ? '启用' : '归档' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleViewStudents(scope.row)">查看学生</el-button>
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="所属学院" prop="collegeId">
          <el-select v-model="form.collegeId" placeholder="请选择所属学院" style="width: 100%" @change="handleCollegeChange">
            <el-option
              v-for="college in collegeOptions"
              :key="college.id"
              :label="college.name"
              :value="college.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属专业" prop="majorId">
          <el-select v-model="form.majorId" placeholder="请选择所属专业" style="width: 100%">
            <el-option
              v-for="major in majorOptions"
              :key="major.id"
              :label="major.name"
              :value="major.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="form.grade" />
        </el-form-item>
        <el-form-item label="学期" prop="semester">
          <el-input v-model="form.semester" />
        </el-form-item>
        <el-form-item label="班主任" prop="headTeacherId">
          <el-select v-model="form.headTeacherId" placeholder="请选择班主任" style="width: 100%">
            <el-option
              v-for="teacher in teacherOptions"
              :key="teacher.id"
              :label="teacher.name"
              :value="teacher.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="毕业状态" prop="graduationStatus">
          <el-select v-model="form.graduationStatus" placeholder="请选择毕业状态" style="width: 100%">
            <el-option label="在读" value="studying" />
            <el-option label="已毕业" value="graduated" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="启用" value="active" />
            <el-option label="归档" value="archived" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 查看学生对话框 -->
    <el-dialog v-model="studentDialogVisible" :title="`班级 ${currentClass.name} 的学生列表`" width="800px">
      <div style="margin-bottom: 15px;">
        <el-button type="primary" @click="handleAddStudent">新增学生</el-button>
        <el-button @click="handleExportStudents">导出学生</el-button>
      </div>
      <el-table :data="studentList" border style="width: 100%" v-loading="studentLoading">
        <el-table-column prop="studentNo" label="学号" width="150" />
        <el-table-column prop="name" label="姓名" width="150" />
        <el-table-column prop="enrollmentYear" label="入学年份" width="120" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="handleEditStudent(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDeleteStudent(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="studentDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 学生新增/编辑对话框 -->
    <el-dialog v-model="studentDialogVisibleForm" :title="studentDialogTitle" width="500px">
      <el-form :model="studentForm" :rules="studentRules" ref="studentFormRef" label-width="80px">
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="studentForm.studentNo" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" />
        </el-form-item>
        <el-form-item label="学院" prop="collegeId">
          <el-select v-model="studentForm.collegeId" placeholder="请选择学院" style="width: 100%" disabled>
            <el-option
              v-for="college in studentCollegeOptions"
              :key="college.id"
              :label="college.name"
              :value="college.id"
            />
          </el-select>
          <div style="color: #999; font-size: 12px; margin-top: 5px;">学院已固定</div>
        </el-form-item>
        <el-form-item label="专业" prop="majorId">
          <el-select v-model="studentForm.majorId" placeholder="请选择专业" style="width: 100%" disabled>
            <el-option
              v-for="major in studentMajorOptions"
              :key="major.id"
              :label="major.name"
              :value="major.id"
            />
          </el-select>
          <div style="color: #999; font-size: 12px; margin-top: 5px;">专业已固定</div>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="studentForm.classId" placeholder="请选择班级" style="width: 100%" disabled>
            <el-option
              v-for="classItem in [currentClass]"
              :key="classItem.id"
              :label="classItem.name"
              :value="classItem.id"
            />
          </el-select>
          <div style="color: #999; font-size: 12px; margin-top: 5px;">班级已固定为当前班级</div>
        </el-form-item>
        <el-form-item label="入学年份" prop="enrollmentYear">
          <el-date-picker
            v-model="studentForm.enrollmentYear"
            type="year"
            placeholder="选择入学年份"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="studentDialogVisibleForm = false">取消</el-button>
          <el-button type="primary" @click="handleStudentSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
  graduationStatus: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 班级列表
const classList = ref([])

const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 学生相关
const studentDialogVisible = ref(false)
const studentList = ref([])
const studentLoading = ref(false)
const currentClass = reactive({
  id: '',
  name: ''
})

// 学生表单相关
const studentDialogVisibleForm = ref(false)
const studentDialogTitle = ref('')
const isStudentEdit = ref(false)

// 学生下拉选项数据
const studentCollegeOptions = ref([])
const studentMajorOptions = ref([])
const studentClassOptions = ref([])

// 学生表单数据
const studentForm = reactive({
  id: '',
  userId: '',
  studentNo: '',
  name: '',
  collegeId: '',
  majorId: '',
  classId: '',
  enrollmentYear: ''
})

// 学生表单验证规则
const studentRules = {
  studentNo: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  enrollmentYear: [{ required: true, message: '请选择入学年份', trigger: 'change' }]
}

const studentFormRef = ref()

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// 获取班级列表
const fetchClasses = async () => {
  loading.value = true
  try {
    // 添加分页参数和搜索参数
    const params = new URLSearchParams();
    params.append('page', pagination.currentPage - 1); // 后端分页从0开始
    params.append('size', pagination.pageSize);
    
    // 添加搜索参数
    if (searchForm.name) {
      params.append('name', searchForm.name);
    }
    if (searchForm.status) {
      params.append('status', searchForm.status);
    }
    if (searchForm.graduationStatus) {
      params.append('graduationStatus', searchForm.graduationStatus);
    }
    
    const response = await axios.get(`http://localhost:8080/api/classes?${params.toString()}`);
    classList.value = response.data.content.map(classes => ({
      ...classes,
      createTime: formatDate(classes.createdAt)
    }))
    pagination.total = response.data.totalElements
  } catch (error) {
    console.error('获取班级列表失败:', error)
    ElMessage.error('获取班级列表失败')
  } finally {
    loading.value = false
  }
}

// 获取学院列表
const fetchStudentColleges = async () => {
  try {
    // 添加分页参数，获取所有学院
    const params = new URLSearchParams();
    params.append('page', 0); // 获取第一页
    params.append('size', 1000); // 设置一个较大的页面大小以获取所有学院
    
    const response = await axios.get(`http://localhost:8080/api/colleges?${params.toString()}`);
    // 处理分页响应数据
    studentCollegeOptions.value = response.data.content || response.data;
  } catch (error) {
    console.error('获取学院列表失败:', error);
    ElMessage.error('获取学院列表失败');
  }
}

// 根据学院ID获取专业列表
const fetchStudentMajorsByCollegeId = async (collegeId) => {
  try {
    const response = await axios.get(`http://localhost:8080/api/majors/college/${collegeId}`);
    studentMajorOptions.value = response.data;
  } catch (error) {
    console.error('获取专业列表失败:', error);
    ElMessage.error('获取专业列表失败');
  }
}

// 根据专业ID获取班级列表
const fetchStudentClassesByMajorId = async (majorId) => {
  try {
    const response = await axios.get(`http://localhost:8080/api/classes/major/${majorId}`);
    studentClassOptions.value = response.data;
  } catch (error) {
    console.error('获取班级列表失败:', error);
    ElMessage.error('获取班级列表失败');
  }
}

// 当学院选择改变时
const handleStudentCollegeChange = (collegeId) => {
  // 清空专业和班级的选择
  studentForm.majorId = '';
  studentForm.classId = '';
  studentMajorOptions.value = [];
  studentClassOptions.value = [];
  
  // 如果选择了学院，则加载该学院下的专业
  if (collegeId) {
    fetchStudentMajorsByCollegeId(collegeId);
  }
}

// 当专业选择改变时
const handleStudentMajorChange = (majorId) => {
  // 清空班级的选择
  studentForm.classId = '';
  studentClassOptions.value = [];
  
  // 如果选择了专业，则加载该专业下的班级
  if (majorId) {
    fetchStudentClassesByMajorId(majorId);
  }
}

// 查看学生
const handleViewStudents = async (row) => {
  studentDialogVisible.value = true
  currentClass.id = row.id
  currentClass.name = row.name
  studentLoading.value = true
  studentList.value = []
  
  try {
    const response = await axios.get(`http://localhost:8080/api/students/class/${row.id}`)
    studentList.value = response.data
  } catch (error) {
    console.error('获取学生列表失败:', error)
    ElMessage.error('获取学生列表失败')
  } finally {
    studentLoading.value = false
  }
}

// 新增学生
const handleAddStudent = async () => {
  studentDialogTitle.value = '新增学生'
  isStudentEdit.value = false
  // 重置表单
  Object.keys(studentForm).forEach(key => {
    studentForm[key] = ''
  })
  // 设置当前班级
  studentForm.classId = currentClass.id
  studentDialogVisibleForm.value = true
  // 加载学院下拉选项数据
  await fetchStudentColleges()
  
  // 如果当前班级有对应的学院和专业信息，加载它们
  try {
    const classResponse = await axios.get(`http://localhost:8080/api/classes/${currentClass.id}`)
    const classInfo = classResponse.data
    if (classInfo.collegeId) {
      studentForm.collegeId = classInfo.collegeId
      await fetchStudentMajorsByCollegeId(classInfo.collegeId)
      if (classInfo.majorId) {
        studentForm.majorId = classInfo.majorId
        // 加载班级选项（虽然在UI上是禁用的，但为了数据一致性）
        await fetchStudentClassesByMajorId(classInfo.majorId)
      }
    }
  } catch (error) {
    console.error('获取班级详情失败:', error)
  }
}

// 编辑学生
const handleEditStudent = async (row) => {
  studentDialogTitle.value = '编辑学生'
  isStudentEdit.value = true
  // 填充表单数据
  studentForm.id = row.id
  studentForm.userId = row.userId
  studentForm.studentNo = row.studentNo
  studentForm.name = row.name
  studentForm.collegeId = row.collegeId
  studentForm.majorId = row.majorId
  studentForm.classId = row.classId
  studentForm.enrollmentYear = row.enrollmentYear
  studentDialogVisibleForm.value = true
  // 加载下拉选项数据
  await fetchStudentColleges()
  
  // 如果有学院ID，加载该学院下的专业
  if (row.collegeId) {
    await fetchStudentMajorsByCollegeId(row.collegeId);
  }
  
  // 如果有专业ID，加载该专业下的班级
  if (row.majorId && row.collegeId) {
    // 验证专业是否属于当前学院
    const isValidMajor = studentMajorOptions.value.some(major => major.id === row.majorId);
    if (isValidMajor) {
      await fetchStudentClassesByMajorId(row.majorId);
    }
  }
}

// 删除学生
const handleDeleteStudent = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除学生 ${row.name} 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端API删除
    await axios.delete(`http://localhost:8080/api/students/${row.id}`)
    ElMessage.success('删除成功')
    
    // 重新加载学生列表
    await reloadStudentList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除学生失败:', error)
      ElMessage.error('删除学生失败')
    }
  }
}

// 重新加载学生列表
const reloadStudentList = async () => {
  studentLoading.value = true
  try {
    const response = await axios.get(`http://localhost:8080/api/students/class/${currentClass.id}`)
    studentList.value = response.data
  } catch (error) {
    console.error('获取学生列表失败:', error)
    ElMessage.error('获取学生列表失败')
  } finally {
    studentLoading.value = false
  }
}

// 提交学生表单
const handleStudentSubmit = async () => {
  if (!studentFormRef.value) return
  
  await studentFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保班级ID设置为当前班级
        studentForm.classId = currentClass.id;
        
        // 格式化入学年份
        let enrollmentYear = studentForm.enrollmentYear;
        if (enrollmentYear instanceof Date) {
          enrollmentYear = enrollmentYear.getFullYear();
        } else if (typeof enrollmentYear === 'string') {
          enrollmentYear = parseInt(enrollmentYear, 10);
        } else if (typeof enrollmentYear === 'number') {
          // 已经是数字，保持不变
        }
        
        if (isStudentEdit.value) {
          // 编辑操作 - 直接更新学生信息
          const studentData = {
            userId: studentForm.userId,
            studentNo: studentForm.studentNo,
            collegeId: studentForm.collegeId,
            majorId: studentForm.majorId,
            classId: studentForm.classId,
            enrollmentYear: enrollmentYear
          };
          
          // 同时更新用户表中的姓名信息
          const userData = {
            realName: studentForm.name
          };
          
          // 并行更新学生和用户信息
          await Promise.all([
            axios.put(`http://localhost:8080/api/students/${studentForm.id}`, studentData),
            axios.put(`http://localhost:8080/api/users/${studentForm.userId}`, userData)
          ]);
          
          ElMessage.success('编辑成功')
        } else { 
          // 新增操作 - 先创建用户，再创建学生
          // 获取当前时间
          const now = new Date().toISOString();
          
          // 1. 创建用户
          const userData = {
            username: studentForm.studentNo, // 使用学号作为用户名
            realName: studentForm.name,
            gender: '男', // 默认值改为数据库允许的值
            role: 'student',
            status: 'active',
            password: '$2a$10$7JB720yubVSOfvK5j6s0oOjGHOOzn2oLs1yLowJO0aPjJ9zJ5jEAu', // 默认密码123456的哈希值
            createdAt: now,
            updatedAt: now
          };
          
          const userResponse = await axios.post('http://localhost:8080/api/users', userData);
          const userId = userResponse.data.id;
          
          // 2. 创建学生记录
          const studentData = {
            userId: userId,
            studentNo: studentForm.studentNo,
            collegeId: studentForm.collegeId, // 使用当前班级的学院ID
            majorId: studentForm.majorId, // 使用当前班级的专业ID
            classId: studentForm.classId, // 确保使用当前班级ID
            enrollmentYear: enrollmentYear
          };
          
          await axios.post('http://localhost:8080/api/students', studentData)
          ElMessage.success('新增成功')
        }
        studentDialogVisibleForm.value = false
        await reloadStudentList() // 重新加载数据
      } catch (error) {
        console.error('操作失败:', error)
        console.error('Response data:', error.response?.data);
        ElMessage.error('操作失败: ' + (error.response?.data?.message || error.response?.data || error.message))
      }
    }
  })
}

// 学院选择变化时的处理
const handleCollegeChange = (collegeId) => {
  // 清空已选择的专业
  form.majorId = '';
  // 根据选择的学院加载对应的专业列表
  if (collegeId) {
    fetchMajors(collegeId);
  } else {
    // 如果没有选择学院，则加载所有专业
    fetchMajors();
  }
}

// 搜索
const handleSearch = async () => {
  console.log('搜索:', searchForm)
  // 重置到第一页
  pagination.currentPage = 1
  await fetchClasses()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  searchForm.graduationStatus = ''
  // 重置到第一页
  pagination.currentPage = 1
  fetchClasses()
}

// 刷新
const handleRefresh = () => {
  fetchClasses()
}

// 新增
const handleAdd = async () => {
  dialogTitle.value = '新增班级'
  isEdit.value = false
  // 重置表单
  Object.keys(form).forEach(key => {
    form[key] = key === 'status' ? 'active' : key === 'graduationStatus' ? 'studying' : ''
  })
  dialogVisible.value = true
  // 加载下拉选项数据
  await Promise.all([fetchColleges(), fetchMajors(), fetchTeachers()])
}

// 编辑
const handleEdit = async (row) => {
  dialogTitle.value = '编辑班级'
  isEdit.value = true
  // 填充表单数据
  form.id = row.id
  form.name = row.name
  form.code = row.code
  form.collegeId = row.collegeId
  form.majorId = row.majorId
  form.grade = row.grade
  form.semester = row.semester
  form.headTeacherId = row.headTeacherId
  form.graduationStatus = row.graduationStatus
  form.status = row.status
  dialogVisible.value = true
  // 加载下拉选项数据
  await Promise.all([fetchColleges(), fetchMajors(), fetchTeachers()])
  
  // 如果有学院ID，加载对应的专业列表
  if (row.collegeId) {
    await fetchMajors(row.collegeId);
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    // 检查班级是否有学生
    if (row.studentCount > 0) {
      ElMessageBox.confirm(
        `班级 ${row.name} 下还有 ${row.studentCount} 名学生，无法直接删除。是否要查看该班级的学生列表？`,
        '无法删除',
        {
          confirmButtonText: '查看学生',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 用户选择查看学生列表
        handleViewStudents(row);
      }).catch(() => {
        // 用户选择取消，不执行任何操作
      });
      return;
    }
    
    await ElMessageBox.confirm(
      `确定要删除班级 ${row.name} 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端API删除
    const response = await axios.delete(`http://localhost:8080/api/classes/${row.id}`)
    ElMessage.success(response.data)
    // 重置到第一页并重新加载数据
    pagination.currentPage = 1
    fetchClasses()
  } catch (error) {
    if (error.response && error.response.status === 400) {
      // 处理后端返回的错误信息
      ElMessage.error(error.response.data)
    } else if (error !== 'cancel') {
      console.error('删除班级失败:', error)
      ElMessage.error('删除班级失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑操作
          await axios.put(`http://localhost:8080/api/classes/${form.id}`, {
            name: form.name,
            code: form.code,
            collegeId: form.collegeId,
            majorId: form.majorId,
            grade: form.grade,
            semester: form.semester,
            headTeacherId: form.headTeacherId,
            graduationStatus: form.graduationStatus,
            status: form.status
          })
          ElMessage.success('编辑成功')
        } else {
          // 新增操作
          // 生成班级代码
          const classCode = generateClassCode(form.name, form.grade);
          await axios.post('http://localhost:8080/api/classes', {
            name: form.name,
            code: classCode,
            collegeId: form.collegeId,
            majorId: form.majorId,
            grade: form.grade,
            semester: form.semester,
            headTeacherId: form.headTeacherId,
            graduationStatus: form.graduationStatus,
            status: form.status
          })
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        // 重置到第一页并重新加载数据
        pagination.currentPage = 1
        fetchClasses()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 导出学生列表
const handleExportStudents = async () => {
  try {
    // 发起导出请求
    const response = await axios({
      method: 'get',
      url: `http://localhost:8080/api/students/class/${currentClass.id}/export`,
      responseType: 'blob' // 重要：设置响应类型为blob
    });
    
    // 创建下载链接
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `班级_${currentClass.name}_学生列表.xlsx`;
    link.click();
    
    // 清理URL对象
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败: ' + (error.response?.data?.message || error.message));
  }
};

// 分页相关
const handleSizeChange = (val) => {
  pagination.pageSize = val
  // 重置到第一页
  pagination.currentPage = 1
  fetchClasses()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchClasses()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchClasses()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>